﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Cognex.DataMan.SDK;
using Cognex.DataMan.SDK.Utils;

using System.Net.Sockets;
using System.Net;

using System.Xml;



namespace DMCC
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        EthSystemConnector myConn;

        DataManSystem _system;

        
  

        private ResultCollector _results;
        public MainWindow()
        {
            InitializeComponent();
            btnEnabled(false);
           
        }


     

        private void btnConnect_Click(object sender, RoutedEventArgs e)
        {

             try
             {
                 IPAddress deviceIP = IPAddress.Parse(textBox1.Text.Trim());
                 myConn = new EthSystemConnector(deviceIP);
                 _system = new DataManSystem(myConn);





                 // Subscribe to events that are signalled when the device sends auto-responses.
                 ResultTypes requested_result_types = ResultTypes.ReadXml | ResultTypes.Image | ResultTypes.ImageGraphics;
                 _results = new ResultCollector(_system, requested_result_types);
                 _results.ComplexResultCompleted += new ComplexResultCompletedEventHandler(_results_ComplexResultCompleted);
                 _results.SimpleResultDropped += new SimpleResultDroppedEventHandler(_results_SimpleResultDropped);





                 //_system.SetKeepAliveOptions(cbEnableKeepAlive.Checked, 3000, 1000);

                

                 _system.Connect();


                 _system.SetResultTypes(requested_result_types);

                 btnEnabled(true);

             }
             catch (Exception ex)
             {
                 MessageBox.Show(ex.Message);
             }


        
        }

        void _results_SimpleResultDropped(object sender, SimpleResult e)
        {
           // throw new NotImplementedException();
        }

        void _results_ComplexResultCompleted(object sender, ComplexResult e)
        {
            //throw new NotImplementedException();

            ShowResult(e);
        }


        private void ShowResult(ComplexResult complexResult)
        {
            List<Image> images = new List<Image>();
            List<string> image_graphics = new List<string>();
            string read_result = null;
            int result_id = -1;
            ResultTypes collected_results = ResultTypes.None;

            // Take a reference or copy values from the locked result info object. This is done
            // so that the lock is used only for a short period of time.
           
                foreach (var simple_result in complexResult.SimpleResults)
                {
                    collected_results |= simple_result.Id.Type;

                    switch (simple_result.Id.Type)
                    {
                        case ResultTypes.Image:
                            //Image image = ImageArrivedEventArgs.GetImageFromImageBytes(simple_result.Data);
                            //if (image != null)
                            //    images.Add(image);
                            break;

                        case ResultTypes.ImageGraphics:
                            image_graphics.Add(simple_result.GetDataAsString());
                            break;

                        case ResultTypes.ReadXml:
                            read_result = GetReadStringFromResultXml(simple_result.GetDataAsString());
                            result_id = simple_result.Id.Id;
                            break;

                        case ResultTypes.ReadString:
                            read_result = simple_result.GetDataAsString();
                            result_id = simple_result.Id.Id;
                            break;
                    }
                }



                if (read_result != null)
                {
                    Dispatcher.Invoke(new Action(() => {

                        lbReadString.Content = read_result;
                    
                    }));
                }
               
        }


        private string GetReadStringFromResultXml(string resultXml)
        {
            try
            {
                XmlDocument doc = new XmlDocument();

                doc.LoadXml(resultXml);

                XmlNode full_string_node = doc.SelectSingleNode("result/general/full_string");

                if (full_string_node != null && _system != null && _system.State == ConnectionState.Connected)
                {
                    XmlAttribute encoding = full_string_node.Attributes["encoding"];
                    if (encoding != null && encoding.InnerText == "base64")
                    {
                        if (!string.IsNullOrEmpty(full_string_node.InnerText))
                        {
                            byte[] code = Convert.FromBase64String(full_string_node.InnerText);
                            return _system.Encoding.GetString(code, 0, code.Length);
                        }
                        else
                        {
                            return "";
                        }
                    }

                    return full_string_node.InnerText;
                }
            }
            catch
            {
            }

            return "";
        }

      
       


       /// <summary>
       /// 按钮使能
       /// </summary>
       /// <param name="flag"></param>
        void btnEnabled(bool flag)
        {
            btnConnect.IsEnabled = !flag;

            btnTrigger.IsEnabled = flag;

            button1.IsEnabled = flag;
        }

        private void btnTrigger_Click(object sender, RoutedEventArgs e)
        {
            if (_system != null)
            {
                _system.SendCommand("TRIGGER ON");
            }

        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            if (_system != null)
            {
              
                _system.Disconnect();
                btnEnabled(false);
            }
        }


        
    }
}
